<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
const route = useRouter();
import { ElMessage, ElMessageBox } from 'element-plus' // 优化更新
import { Search, Delete, Files, Plus, Connection, Document, EditPen } from '@element-plus/icons-vue'	//导入Search图标
import { PlantsPage, BaseData, resourceDelete, statistics, plantexport } from '@/utils/api.js' // 优化更新

// 优化更新
import haForm from '../common/ha-form.vue';

import sjj from '@/assets/img/sjj.png'
import gyy from '@/assets/img/gyy.png'
import gye from '@/assets/img/gye.png'

const haf = ref(null);
const multipleSelection = ref([]);


// 事件

const fltgyy = (item, data) => {
    let str = '';
    if (item == '国家一级') {
        str = gyy
    } else if (item == '国家二级') {
        str = gye
    } else if (item == '北京市级') {
        str = sjj
    } else {
        str = data.coverImage
    }

    return str
}

const delItem = (item) => {
    ElMessageBox.confirm(
        '确定要删除这条数据吗?',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            resourceDelete({
                resourceType: "plant",
                ids: item
            }).then((res) => {
                if (res.code == '200') {
                    ElMessage({
                        type: 'success',
                        message: '删除成功',
                    })
                    getAnimalsPage();
                } else {
                    ElMessage({
                        type: 'warning',
                        message: res.msg,
                    })
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}


// 优化更新
// 分页 B
const pageSize = ref(10);
const pageNum = ref(1);
const totalElements = ref(100);
const currentPage = ref(1);

const setBrackets = (data) =>{
    let cleanedData = data.map(item => item.replace(/\s*（.*?）/, ''));
    gang.value = cleanedData
}

const resp = () => {
    pageNum.value = 1;
    currentPage.value = 1;
    setBrackets(gang.value)
    getBaseData();
    getstatistics()
}

const handleSelectionSelectAll = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

const handleSelectionSelect = (val) => {
    let arr = []
    val.forEach(e => {
        arr.push(e.id)
    })
    multipleSelection.value = arr;
}

const handleCurrentChange = (val) => {
    pageNum.value = val;
    getAnimalsPage();
};
// 分页 E
const godetails = (data) => {
    let planthis = {
        "pageSize": pageSize.value,
        "pageNum": pageNum.value,
        "level": level.value,
        "men": men.value,
        "gang": gang.value,
        "mu": mu.value,
        "ke": ke.value,
        "shu": shu.value,
        "keywords": keywords.value,
        "areaDistribution": areaDistribution.value,
        "iucn": iucn.value,
        "currentPage": currentPage.value,
    }
    window.sessionStorage.setItem('planthis', JSON.stringify(planthis));
    route.push({ path: '/plants/plantdetails', query: { id: data.id } });
};

const men = ref([]);
const gang = ref([]);
const mu = ref([]);
const ke = ref([]);
const shu = ref([]);
const level = ref([]);
const areaDistribution = ref('');
const iucn = ref([]);
const keywords = ref('');
const optionObj = ref({
    gangs: [],
    kes: [],
    levels: [],
    mens: [],
    mus: [],
    shus: []
});

const getBaseData = async () => {
    let data = await BaseData('plant', usermsg.areaId, men.value, gang.value, mu.value, ke.value, shu.value, level.value)
    optionObj.value = data.data;
    let arr = data.data.gangs
    let updatedArr = arr.map(item => {
        if (['木兰纲', '石松纲', '木贼纲', '松纲'].includes(item)) {
            return item + '（维管植物）';
        } else {
            return item + '（藻类）';
        }
    });
    optionObj.value.gangs = updatedArr
    getAnimalsPage();
};

const list = ref([]);

const getAnimalsPage = async () => {
    let areaDistributions = areaDistribution.value;
    if (areaDistributions == '北京市') {
        areaDistributions = ''
    }
    let obj = {
        "areaId": usermsg.areaId,
        "pageSize": pageSize.value,
        "pageNum": pageNum.value,
        "level": level.value,
        "men": men.value,
        "gang": gang.value,
        "mu": mu.value,
        "ke": ke.value,
        "shu": shu.value,
        "keywords": keywords.value,
        "areaDistribution": areaDistributions,
        "iucn": iucn.value
    }
    let res = await PlantsPage(obj)
    if (res.code == '200') {
        list.value = res.data.content;
        totalElements.value = res.data.totalElements;
        // 优化更新
        multipleSelection.value = []
    } else {
        ElMessage({
            message: res.message,
            type: 'warning',
        })
        list.value = []
    }
};

const statisticsResourceType = ref(null)

const getstatistics = async () => {
    let res = await statistics({
        "areaId": usermsg.areaId,
        "level": level.value,
        "men": men.value,
        "gang": gang.value,
        "mu": mu.value,
        "ke": ke.value,
        "shu": shu.value,
        "keywords": keywords.value,
        "areaDistribution": '',
        "iucn": iucn.value,
        "resourceType": "plant"
    })
    statisticsResourceType.value = res.data;
}

const exportAnis = async () => {
    let params = {
        "areaId": usermsg.areaId,
        "pageSize": pageSize.value,
        "pageNum": pageNum.value,
        "level": level.value,
        "men": men.value,
        "gang": gang.value,
        "mu": mu.value,
        "ke": ke.value,
        "shu": shu.value,
        "keywords": keywords.value,
        "areaDistribution": areaDistribution.value,
        "iucn": iucn.value,
    }

    let res = await plantexport(params)

    // 解析文件名
    const str = res.headers['content-disposition'].split(';')[1].split('=')[1];
    const filename = decodeURIComponent(str);
    // 用blob存储二进制文件
    const blob = new Blob([res.data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8', // 设置文件类型 pdf是application/pdf，word是application/vnd.openxmlformats-officedocument.wordprocessingml.document，其他类型可以百度一下
    });
    // 创建一个临时的url指向blob对象
    const objectUrl = window.URL.createObjectURL(blob);
    // 创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
    const a = document.createElement('a');
    a.setAttribute('href', objectUrl);
    a.setAttribute('download', filename);
    a.click();
    // 5.释放这个临时的对象url
    window.URL.revokeObjectURL(objectUrl);
}

let usermsg = '';
onMounted(() => {
    usermsg = window.sessionStorage.getItem('usermsg');
    if (usermsg == undefined) {
        alert('您无权查看该网站，请登录后才能正常使用')
    } else {
        usermsg = JSON.parse(usermsg);
    };
    if (window.sessionStorage.getItem('planthis') != null) {
        let data = JSON.parse(window.sessionStorage.getItem('planthis'));
        pageSize.value = data.pageSize;
        pageNum.value = data.pageNum;
        level.value = data.level;
        men.value = data.men;
        gang.value = data.gang;
        mu.value = data.mu;
        ke.value = data.ke;
        shu.value = data.shu;
        keywords.value = data.keywords;
        areaDistribution.value = data.areaDistribution;
        iucn.value = data.iucn;
        currentPage.value = data.currentPage;
        getBaseData();
        window.sessionStorage.removeItem('planthis');
    } else {
        getBaseData();
    }

    getstatistics()
})
</script>
<template>
    <div>
        <div class="ha-title">
            <div>
                <span>植物资源</span>
            </div>
            <!-- 优化更新 -->
            <div>
                <el-button :icon="Delete" @click="delItem(multipleSelection)" plain>删除({{ multipleSelection.length
                    }})</el-button>
                <el-button :icon="Files" @click="exportAnis" plain>导出</el-button>
                <el-button :icon="Plus" plain @click.stop="haf.openform('', '新增', 'plant', optionObj)">新增物种</el-button>
            </div>
        </div>

        <div class="resourceClassify" v-if="statisticsResourceType">
            <div class="rcc1">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    物种数量(种)
                </span>
                <span>
                    {{ statisticsResourceType.zhong.count }}
                </span>
            </div>
            <div class="rcc1">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    纲(个)
                </span>
                <span>
                    {{ statisticsResourceType.gang.count }}
                </span>
            </div>
            <div class="rcc1">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    目(个)
                </span>
                <span>
                    {{ statisticsResourceType.mu.count }}
                </span>
            </div>
            <div class="rcc1">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    科(个)
                </span>
                <span>
                    {{ statisticsResourceType.ke.count }}
                </span>
            </div>
            <div class="rcc1">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    属(个)
                </span>
                <span>
                    {{ statisticsResourceType.shu.count }}
                </span>
            </div>
            <div class="rcc2">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    国家一级(种)
                </span>
                <span>
                    {{ statisticsResourceType.levelOne.count }}
                </span>
            </div>
            <div class="rcc3">
                <el-icon>
                    <Connection />
                </el-icon>
                <span class="resourceClassifyName">
                    国家二级(种)
                </span>
                <span>
                    {{ statisticsResourceType.levelTwo.count }}
                </span>
            </div>
        </div>



        <el-row :gutter="10">
            <el-col :span="3">
                <el-select v-model="level" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="保护等级"
                    multiple collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.levels" :key="item" :label="item" :value="item" />
                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="iucn" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="IUCN筛选"
                    multiple collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.iucns" :key="item" :label="item" :value="item" />
                </el-select>
            </el-col>
            <!-- <el-col :span="2">
                    <el-select v-model="areaDistribution" class="m-2" clearable @change="getBaseData()" placeholder="选择区域"
                        size="large">
                        <el-option label="北京市" value="北京市" />
                        <el-option label="密云区" value="密云区" />
                    </el-select>
                </el-col> 
            <el-col :span="3">
                <el-select v-model="men" class="m-2" clearable @change="resp()" placeholder="选择门" size="large">
                    <el-option v-for="item in optionObj.mens" :key="item" :label="item.label" :value="item" />
                </el-select>
            </el-col>-->
            <el-col :span="3">
                <el-select v-model="gang" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="选择纲"
                    multiple collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.gangs" :key="item" :label="item.label" :value="item" />
                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="mu" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="选择目" multiple
                    collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.mus" :key="item" :label="item.label" :value="item" />
                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="ke" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="选择科" multiple
                    collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.kes" :key="item" :label="item.label" :value="item" />
                </el-select>
            </el-col>
            <el-col :span="3">
                <el-select v-model="shu" class="m-2" clearable @blur="resp()" @clear="resp()" placeholder="选择属" multiple
                    collapse-tags collapse-tags-tooltip size="large">
                    <el-option v-for="item in optionObj.shus" :key="item" :label="item.label" :value="item" />
                </el-select>
            </el-col>
            <el-col :span="1"></el-col>
            <el-col :span="5">
                <el-input v-model="keywords" placeholder="搜索物种" size="large" class="input-with-select">
                    <template #append>
                        <el-button @click.stop="resp()" :icon="Search" />
                    </template>
                </el-input>
            </el-col>

        </el-row>

        <el-table :data="list" @select-all="handleSelectionSelectAll" @select="handleSelectionSelect"
            style="width: 100%;margin-top: 16px;height: calc(100% - 180px);"
            :header-cell-style="{ 'color': '#333', 'line-height': '40px' }">
            <el-table-column type="selection" width="35" />
            <el-table-column label="物种" width="320">
                <template #default="scope">
                    <div class="tb-sh">
                        <div>
                            <el-badge value="new" :hidden="!scope.row.isNew" class="item">
                                <img :src="fltgyy(scope.row.level, scope.row)" alt="">
                            </el-badge>
                        </div>
                        <div>
                            <span style="color: black;">{{ scope.row.zhong }}</span>
                            <el-button v-if="scope.row.endangeredLevel" style="margin-left: 8px;color: #409eff;" plain
                                size="small">{{
                                    scope.row.endangeredLevel }}</el-button>
                            <br />
                            <span style="font-style: italic;">{{
                                scope.row.zhongLatinName }}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <!-- <el-table-column label="最新拍摄日期" prop="recordNumber" width="120" /> -->
            <el-table-column label="纲" prop="gang" show-overflow-tooltip />
            <el-table-column label="目" prop="mu" show-overflow-tooltip />
            <el-table-column label="科" prop="ke" show-overflow-tooltip />
            <el-table-column label="属" prop="shu" show-overflow-tooltip />


            <!-- <el-table-column label="保护等级" prop="status">
                <template #default="scope">
                    <el-button v-if="scope.row.level == '国家二级'" class="rcc3">
                        {{ scope.row.level }}
                    </el-button>
                    <el-button v-else-if="scope.row.level == '国家一级'" class="rcc2">
                        {{ scope.row.level }}
                    </el-button>

                    <el-button v-else style="border: none;">
                        {{ scope.row.level }}
                    </el-button>
                </template>
            </el-table-column>
            <el-table-column label="IUCN名录" prop="endangeredLevel" /> -->

            <el-table-column label="操作" fixed="right" width="240">
                <!-- // 优化更新 -->
                <template #default="scope">
                    <el-button type="info" @click.stop="godetails(scope.row)" :icon="Document" plain size="small">
                        详情
                    </el-button>
                    <el-button type="info" plain :icon="EditPen"
                        @click.stop="haf.openform(scope.row, '修改', 'plant', optionObj)" size="small">
                        修改
                    </el-button>
                    <el-button type="info" plain :icon="Delete" @click.stop="delItem([scope.row.id])" size="small">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 B-->
        <div class="ml-page">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" background
                layout="total, prev, pager, next, jumper" :total="totalElements"
                @current-change="handleCurrentChange" />
        </div>
        <!-- 分页 E-->

        <!-- // 优化更新 -->
        <!-- 新增修改 -->
        <ha-form ref="haf" @refreshList="resp()" />
        <!-- 新增修改 -->

    </div>
</template>
<style scoped></style>